package com.auctionhaus

import grails.converters.*
import auctionhaus.BidService

class BidController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def bidService

    def index = {
        redirect(action: "list", params: params)
    }

    def xmlList = {
          render Bid.list() as XML
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [bidInstanceList: Bid.list(params), bidInstanceTotal: Bid.count()]
    }

    def create = {
        def bidInstance = new Bid()
        bidInstance.properties = params
        return [bidInstance: bidInstance]
    }

    def placeBid = {
        params.date = new Date()
        params.buyer = Customer.findByEmailAddressIlike(params.buyerEmailAddress)
        def validAmount = (params.amount.toString().number ?  params.amount.toDouble() : null)
        def listingInstance = Listing.findByListName(params.selectedListName)
        def nextBidPrice = listingInstance?.getNextBidPrice()

        def bidInstance = bidService.placeBidOnListing(params.selectedListName, params.buyerEmailAddress, params.buyer.password, validAmount)
        listingInstance = Listing.findByListName(params.selectedListName)

        if (listingInstance.endDateTime < params.date || !bidInstance) {
            if (!listingInstance || listingInstance.endDateTime < params.date){
                flash.message = "Bid Rejected. ${params.selectedListName} is no longer an active listing."
            }
            if (!params.buyer) {
                flash.message = "Bid Rejected. ${params.buyerEmailAddress} is not a registered AuctionHaus user."
            }
            else if (!params.amount.toString().number){
                flash.message = 'Bid Rejected. Bid Amount must be a valid number'
            }
            else if (params.amount.asType(Double) < nextBidPrice) {
                flash.message = 'Bid Rejected. Bid Amount must be at least ' + nextBidPrice
            }
           render(template:"/listing/showWinningBid",  model:[listingInstance:listingInstance, bidInstance: bidInstance])
        }
        else
        {
            // Now redirect
            flash.message = 'Bid Placed Successfully.'
            listingInstance.bids = Bid.findAllByListing(listingInstance)
            render(template:"/listing/showWinningBid",  model:[listingInstance:listingInstance])
        }
    }

    def save = {
        params.date = new Date()
        def listingInstance = Listing.findByListName(params.selectedListName)
        params.listing = listingInstance
        params.buyer = Customer.findByEmailAddressIlike(params.buyerEmailAddress)
        def bidInstance = new Bid(params)
        def nextBidPrice = listingInstance.getNextBidPrice()
        if (bidInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'bid.label', default: 'Bid'), bidInstance.id])}"
            redirect(action: "show", id: bidInstance.id)
        }
        else {
            if (!params.buyer) {
                flash.message = "${params.buyerEmailAddress} is not a registered AuctionHaus user."
            }
            else if (params.amount.asType(Double) < nextBidPrice) {
                flash.message = 'Bid Amount must be at least ' + nextBidPrice
            }
            render(view: "create", model: [bidInstance: bidInstance])
        }
    }

    def show = {
        def bidInstance = Bid.get(params.id)
        if (!bidInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
        else {
            [bidInstance: bidInstance]
        }
    }

    def edit = {
        def bidInstance = Bid.get(params.id)
        if (!bidInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [bidInstance: bidInstance]
        }
    }

    def update = {
        def bidInstance = Bid.get(params.id)
        if (bidInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (bidInstance.version > version) {
                    
                    bidInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'bid.label', default: 'Bid')] as Object[], "Another user has updated this Bid while you were editing")
                    render(view: "edit", model: [bidInstance: bidInstance])
                    return
                }
            }
            bidInstance.properties = params
            if (!bidInstance.hasErrors() && bidInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'bid.label', default: 'Bid'), bidInstance.id])}"
                redirect(action: "show", id: bidInstance.id)
            }
            else {
                render(view: "edit", model: [bidInstance: bidInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def bidInstance = Bid.get(params.id)
        if (bidInstance) {
            try {
                bidInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
    }
}
